package cn.tjie.org.service.impl;

import cn.tjie.basic.service.impl.BaseServiceImpl;
import cn.tjie.org.domain.Department;
import cn.tjie.org.mapper.DepartmentMapper;
import cn.tjie.org.query.DepartmentQuery;
import cn.tjie.org.service.DepartmentService;
import cn.tjie.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务层的实现类：部门
 */
@Service//service 创建实例
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 无限极树，多层级的上级部门的查询业务
     * @return
     */
    @Override
    public List<Department> deptTree() {
        //将所有部门信息保存在map中，方便根据id去获取部门信息，就不用查数据库了
        List<Department> departments = departmentMapper.loadAll();
        Map<Long,Department> map = new HashMap<>();
        for (Department department : departments) {
            Long id = department.getId();
            map.put(id,department);
        }

        ArrayList<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            //遍历所有部门，如果是顶级部门getParent_id()==null，加到部门数
            if(department.getParent_id()==null){//顶级部门
                deptTree.add(department);//直接加到集合
            }else{
                //如果不是顶级部门，找到自己的父部门，将自己加到父部门的children中
                //获取父部门的id - 获取父部门对象 - 获取父部门的children集合
                Long parent_id = department.getParent_id();
                //根据id获取父部门
                Department parentDepartment= map.get(parent_id);
                if(parentDepartment!=null){
                    parentDepartment.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }
}
